<!-- index.vue -->
<template>
  <div class="staff-editor">
    <!-- 移动端抽屉按钮 -->
    <div v-if="isMobile" class="mobile-drawer-button">
      <el-button 
        type="primary" 
        size="small" 
        @click="drawerVisible = true"
        class="drawer-trigger"
      >
        <el-icon><i-ep-menu /></el-icon>
        <span>人员列表</span>
      </el-button>
    </div>

    <!-- 头部操作栏 -->
    <div class="card-header" :class="{ 'mobile-header': isMobile }">
      <div class="header-left">
        <span class="header-title">编辑人员信息</span>
        <span v-if="currentStaff" class="current-staff-name">
          {{ currentStaff.name }} (ID: {{ currentStaff.id }})
        </span>
      </div>
      <div class="header-actions" :class="{ 'mobile-actions': isMobile }">
        <el-button
          type="success"
          size="small"
          @click="addNewStaff"
          :loading="isLoading"
        >
          <el-icon><i-ep-plus /></el-icon>
          <span v-if="!isMobile">添加</span>
        </el-button>
        <el-button
          type="primary"
          size="small"
          @click="saveStaffInfo"
          :loading="isLoading"
        >
          <el-icon><i-ep-upload-filled /></el-icon>
          <span v-if="!isMobile">保存</span>
        </el-button>
        <el-button size="small" type="info" @click="resetForm">
          <el-icon><i-ep-refresh-left /></el-icon>
          <span v-if="!isMobile">重置</span>
        </el-button>
        <el-button
          type="danger"
          size="small"
          @click="deleteCurrentStaff"
          :disabled="staffList.length <= 1"
          :loading="isLoading"
        >
          <el-icon><i-ep-delete /></el-icon>
          <span v-if="!isMobile">删除</span>
        </el-button>
      </div>
    </div>

    <el-row class="main-container">
      <!-- 左侧人员列表 - 桌面端 -->
      <el-col 
        v-if="!isMobile" 
        :xs="24" :sm="8" :md="6" 
        class="list-column desktop-list"
      >
        <StaffList
          :staff-list="staffList"
          :current-staff-id="currentStaffId"
          :scrollbar-height="scrollbarHeight"
          @staff-select="handleStaffSelect"
        />
      </el-col>

      <!-- 右侧编辑区域 -->
      <el-col 
        :xs="24" 
        :sm="isMobile ? 24 : 16" 
        :md="isMobile ? 24 : 18" 
        class="editor-column"
      >
        <div class="editor-card" v-if="currentStaffCopy">
          <el-scrollbar :height="mobileScrollbarHeight">
            <el-form
              ref="staffForm"
              :model="currentStaffCopy"
              :label-width="formLabelWidth"
              :label-position="isMobile ? 'top' : 'right'"
              class="staff-form"
            >
              <!-- 基本信息 -->
              <BasicInfoForm 
                :form-data="currentStaffCopy" 
                :is-mobile="isMobile" 
              />

              <!-- 资质 -->
              <CheckboxGroup
                label="资质"
                prop="qualificationIds"
                v-model="currentStaffCopy.qualificationIds"
                :options="options.qualifications"
                :is-mobile="isMobile"
                @change="handleQualificationsChange"
              />

              <!-- 组织信息 -->
              <CheckboxGroup
                label="科室"
                prop="organizationIds"
                v-model="currentStaffCopy.organizationIds"
                :options="options.organizations"
                :is-mobile="isMobile"
                @change="handleOrganizationsChange"
              />

              <CheckboxGroup
                label="班组"
                prop="groups"
                v-model="currentStaffCopy.groups"
                :options="options.groups"
                :is-mobile="isMobile"
                @change="handleGroupsChange"
              />

              <!-- 席位信息 -->
              <CheckboxGroup
                label="席位"
                prop="availableSeats"
                v-model="currentStaffCopy.availableSeatIds"
                :options="formattedSeats"
                :is-mobile="isMobile"
                @change="handleAvailableSeatsChange"
              />

              <!-- 临时角色 -->
              <el-form-item 
                label="临时角色列表" 
                :label-width="isMobile ? '0' : undefined"
              >
                <el-table
                  :data="currentStaffCopy.temporaryRoles"
                  border
                  style="width: 100%; margin-bottom: 16px"
                  size="small"
                >
                  <el-table-column 
                    label="时间" 
                    :width="isMobile ? 60 : 80" 
                    align="center"
                  >
                    <template #default="scope">
                      <div :class="{ 'mobile-time-cell': isMobile }">
                        <div>{{ scope.row.from }}</div>
                        <div>至</div>
                        <div>{{ scope.row.to }}</div>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column 
                    prop="qualifications" 
                    label="角色内容"
                    :min-width="isMobile ? 120 : 200"
                  >
                    <template #default="scope">
                      <div :class="{ 'mobile-role-content': isMobile }">
                        <div>{{ scope.row.qualifications.join(", ") }}</div>
                        <div>{{ scope.row.organizations.join(", ") }}</div>
                        <div>{{ scope.row.availableSeats.join(", ") }}</div>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column 
                    label="操作" 
                    :width="isMobile ? 60 : 80" 
                    align="center"
                  >
                    <template #default="scope">
                      <div class="action-buttons">
                        <el-button
                          type="primary"
                          :size="isMobile ? 'small' : 'small'"
                          @click="editTemporaryRole(scope.row, scope.$index)"
                        >
                          <el-icon><i-ep-edit /></el-icon>
                        </el-button>
                        <el-button
                          type="danger"
                          :size="isMobile ? 'small' : 'small'"
                          @click="deleteTemporaryRole(scope.$index)"
                        >
                          <el-icon><i-ep-delete /></el-icon>
                        </el-button>
                      </div>
                    </template>
                  </el-table-column>
                </el-table>

                <el-button
                  type="primary"
                  size="small"
                  @click="addTemporaryRole"
                >
                  <el-icon><i-ep-plus /></el-icon>
                  <span>添加临时角色</span>
                </el-button>
              </el-form-item>

              <!-- 标记信息 -->
              <el-divider content="标记信息" />

              <CheckboxGroup
                label="标记"
                prop="markIds"
                v-model="currentStaffCopy.markIds"
                :options="options.marks"
                :is-mobile="isMobile"
                @change="handleMarksChange"
              />
            </el-form>
          </el-scrollbar>
        </div>
        <div v-else class="editor-empty">
          <el-empty description="请选择一个人员进行编辑"></el-empty>
        </div>
      </el-col>
    </el-row>

    <!-- 移动端人员列表抽屉 -->
    <el-drawer
      v-if="isMobile"
      v-model="drawerVisible"
      title="人员列表"
      direction="ltr"
      size="85%"
    >
      <StaffList
        :staff-list="staffList"
        :current-staff-id="currentStaffId"
        :scrollbar-height="mobileDrawerHeight"
        @staff-select="handleMobileStaffSelect"
      />
    </el-drawer>

    <!-- 临时角色编辑对话框 -->
    <TemporaryRoleDialog
      v-model="temporaryRoleDialogVisible"
      :form-data="currentTemporaryRole"
      :editing-role-index="editingRoleIndex"
      :options="options"
      :is-mobile="isMobile"
      @close="temporaryRoleDialogVisible = false"
      @save="saveTemporaryRole"
      @update:form-data="updateTemporaryRoleData"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import useStaffStore from "@/stores/staffStore";
import useCommonStore from "@/stores/commonStore"; // 引入commonStore
import options from "@/profiles/options.json";
import { storeToRefs } from "pinia";
// 导入组件
import StaffList from "./components/StaffList.vue";
import BasicInfoForm from "./components/BasicInfoForm.vue";
import CheckboxGroup from "./components/CheckboxGroup.vue";
import TemporaryRoleDialog from "./components/TemporaryRoleDialog.vue";

const scrollbarHeight = ref("calc(100vh - 160px)");

// 使用 Pinia store
const staffStore = useStaffStore();
const commonStore = useCommonStore();
const { staffList, currentStaffId, currentStaff, isLoading, error } =
  storeToRefs(staffStore);
const { isMobile } = storeToRefs(commonStore);

// 当前人员的副本（用于编辑）
const currentStaffCopy = ref(null);

// 移动端相关状态
const drawerVisible = ref(false);

// 临时角色对话框相关
const temporaryRoleDialogVisible = ref(false);
const currentTemporaryRole = ref({});
const editingRoleIndex = ref(-1);
const staffForm = ref(null);

// 计算属性
const formattedSeats = computed(() => {
  return options.seats.map((seat) => ({
    id: seat,
    name: seat,
  }));
});

const mobileScrollbarHeight = computed(() => {
  return isMobile.value ? "calc(100vh - 180px)" : "calc(100vh - 160px)";
});

const mobileDrawerHeight = computed(() => {
  return "calc(100vh - 120px)";
});

const formLabelWidth = computed(() => {
  return isMobile.value ? "80px" : "100px";
});

// 监听当前人员变化，更新副本
watch(currentStaff, (newStaff) => {
  if (newStaff) {
    currentStaffCopy.value = JSON.parse(JSON.stringify(newStaff));
  } else {
    currentStaffCopy.value = null;
  }
}, { immediate: true });

// 生成唯一ID（用于临时员工）
const generateTempId = () => {
  return 'temp_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
};

// 选择人员
const handleStaffSelect = (staff) => {
  staffStore.setCurrentStaff(staff.id);
};

// 移动端选择人员
const handleMobileStaffSelect = (staff) => {
  staffStore.setCurrentStaff(staff.id);
  drawerVisible.value = false; // 选择后关闭抽屉
};

// 添加新人员（修改为本地添加）
const addNewStaff = () => {
  const newStaff = {
    name: "新人员",
    id: generateTempId(), // 使用临时ID
    guid: null, // 新增员工没有guid
    isNew: true, // 标记为新员工
    qualifications: [],
    qualificationIds: [],
    organizations: [],
    organizationIds: [],
    groups: [],
    groupIds: [],
    availableSeats: [],
    availableSeatIds: [],
    temporaryRoles: [],
    marks: [],
    markIds: [],
  };

  try {
    staffStore.addStaffLocal(newStaff);
    ElMessage.success("新人员已添加，请填写信息后点击保存");
    // 移动端添加后关闭抽屉
    if (isMobile.value) {
      drawerVisible.value = false;
    }
  } catch (err) {
    ElMessage.error(err.message || "添加人员失败");
  }
};

// 删除当前人员
const deleteCurrentStaff = async () => {
  ElMessageBox.confirm("确定要删除当前人员吗？", "删除确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        // 如果是新员工（本地添加的），直接从列表中删除
        if (currentStaff.value.isNew) {
          const index = staffList.value.findIndex(staff => staff.id === currentStaffId.value);
          if (index !== -1) {
            staffList.value.splice(index, 1);
            if (staffList.value.length > 0) {
              staffStore.setCurrentStaff(staffList.value[0].id);
            } else {
              currentStaffId.value = null;
            }
          }
          ElMessage.success("人员已删除");
        } else {
          // 已保存的员工调用API删除
          await staffStore.deleteStaff(currentStaffId.value);
          ElMessage.success("人员已删除");
        }
      } catch (err) {
        ElMessage.error(err.message || "删除人员失败");
      }
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

// 保存人员信息（修改为区分新建和更新）
const saveStaffInfo = async () => {
  staffForm.value.validate(async (valid) => {
    if (valid && currentStaffCopy.value) {
      try {
        // 如果ID被修改了，需要更新store中的ID
        if (currentStaffCopy.value.id !== currentStaff.value.id) {
          await staffStore.updateStaffWithNewId(
            currentStaff.value.id, // 原ID
            currentStaffCopy.value  // 新数据（包含新ID）
          );
        } else {
          // ID没有变化，正常更新
          if (currentStaff.value.isNew) {
            // 新员工：调用创建API
            await staffStore.createStaffAPI(currentStaffCopy.value);
          } else {
            // 已存在的员工：调用更新API
            await staffStore.updateStaffData(currentStaffCopy.value);
          }
        }
        ElMessage.success("保存成功");
      } catch (err) {
        ElMessage.error(err.message || "保存失败");
      }
    }
  });
};

// 重置表单
const resetForm = () => {
  // 重置副本为原始数据
  if (currentStaff.value) {
    currentStaffCopy.value = JSON.parse(JSON.stringify(currentStaff.value));
  }
  ElMessage.info("表单已重置");
};

// 处理各种变化
const handleQualificationsChange = (values) => {
  currentStaffCopy.value.qualifications = options.qualifications
    .filter((item) => values.includes(item.id))
    .map((item) => item.name);
};

const handleOrganizationsChange = (values) => {
  currentStaffCopy.value.organizations = options.organizations
    .filter((item) => values.includes(item.id))
    .map((item) => item.name);
};

const handleGroupsChange = (values) => {
  currentStaffCopy.value.groups = options.groups
    .filter((item) => values.includes(item.id))
    .map((item) => item.name);
};

const handleAvailableSeatsChange = (values) => {
  currentStaffCopy.value.availableSeats = [...values];
};

const handleMarksChange = (values) => {
  currentStaffCopy.value.marks = options.marks
    .filter((item) => values.includes(item.id))
    .map((item) => item.name);
};

// 临时角色相关方法
const addTemporaryRole = () => {
  currentTemporaryRole.value = {
    from: "00:00",
    to: "00:00",
    qualifications: [],
    qualificationIds: [],
    organizations: [],
    organizationIds: [],
    availableSeats: [],
    availableSeatIds: [],
  };
  editingRoleIndex.value = -1;
  temporaryRoleDialogVisible.value = true;
};

const editTemporaryRole = (role, index) => {
  currentTemporaryRole.value = JSON.parse(JSON.stringify(role));
  editingRoleIndex.value = index;
  temporaryRoleDialogVisible.value = true;
};

const deleteTemporaryRole = (index) => {
  currentStaffCopy.value.temporaryRoles.splice(index, 1);
  ElMessage.success("临时角色已删除");
};

const updateTemporaryRoleData = (newData) => {
  currentTemporaryRole.value = newData;
};

const saveTemporaryRole = () => {
  if (editingRoleIndex.value === -1) {
    // 添加新角色
    currentStaffCopy.value.temporaryRoles.push(
      JSON.parse(JSON.stringify(currentTemporaryRole.value))
    );
  } else {
    // 更新现有角色
    currentStaffCopy.value.temporaryRoles[editingRoleIndex.value] = JSON.parse(
      JSON.stringify(currentTemporaryRole.value)
    );
  }
  temporaryRoleDialogVisible.value = false;
  ElMessage.success("临时角色已保存");
};

// 初始化
onMounted(async () => {
  try {
    await staffStore.loadStaffList();
  } catch (err) {
    ElMessage.error(err.message || "加载人员列表失败");
  }
});
</script>

<style scoped>
.staff-editor {
  box-sizing: border-box;
  height: 100%;
}

.main-container {
  height: 100%;
}

.list-column,
.editor-column {
  height: 100%;
  box-sizing: border-box;
}

.editor-card {
  height: 100%;
  display: flex;
  flex-direction: column;
  border: 1px solid var(--el-border-color-light);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0;
  flex-wrap: wrap;
}

.card-header.mobile-header {
  flex-direction: column;
  align-items: flex-start;
  gap: 12px;
  padding: 12px 0;
}

.header-left {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.header-title {
  font-size: 16px;
  font-weight: 600;
}

.current-staff-name {
  font-size: 14px;
  color: var(--el-text-color-regular);
}

.header-actions {
  display: flex;
  gap: 8px;
}

.header-actions.mobile-actions {
  width: 100%;
  justify-content: space-between;
}

.header-actions.mobile-actions .el-button {
  flex: 1;
  min-width: 0;
}

.mobile-drawer-button {
  padding: 8px 0;
  border-bottom: 1px solid var(--el-border-color-light);
  margin-bottom: 12px;
}

.drawer-trigger {
  width: 100%;
}

.editor-empty {
  padding: 40px 0;
  text-align: center;
}

.staff-form {
  margin-top: 20px;
  overflow-y: auto;
  flex: 1;
  padding-right: 10px;
}

.mobile-time-cell {
  font-size: 12px;
  line-height: 1.2;
}

.mobile-role-content {
  font-size: 12px;
  line-height: 1.4;
}

.mobile-role-content div {
  margin-bottom: 2px;
}

.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

/* 移动端样式优化 */
@media (max-width: 768px) {
  .staff-form {
    margin-top: 12px;
    padding-right: 0;
  }
  
  .editor-card {
    border: none;
  }
  
  .desktop-list {
    display: none;
  }
}
</style>